package Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;

import nl.tue.be.ds.duraark.bSDD.ClientUtilities;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.api.client.UniformInterfaceException;


public class ListTest {
	
	private static List<NewCookie> getCookies(Client client, String loginUrl) {
		WebResource webResource = client
				.resource(loginUrl);
		MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
		formData.add("email", "demo");
		formData.add("password", "demo");

		webResource.accept(MediaType.APPLICATION_JSON_TYPE);
		webResource.type(MediaType.APPLICATION_FORM_URLENCODED);

		ClientResponse response = webResource.type(
				MediaType.APPLICATION_FORM_URLENCODED).post(
				ClientResponse.class, formData);
		
		List<NewCookie> cookies = response.getCookies();
		
		return cookies;
	}
	
	
	private static String searchConcepts(String searchterm, List<NewCookie> cookies) throws Exception {

		String result = null;
		final String searchConceptURL ="http://bsddpilot.catenda.no/api/4.0/IfdConcept/";
		//HashMap<String, String> GuidTypePairs = new HashMap<String, String>();
		
			ClientConfig clientConfig = new DefaultClientConfig();
			clientConfig.getClasses().add(JacksonJsonProvider.class);
			clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
			Client client = Client.create(clientConfig);
			//String s = URLEncoder.encode("*", "UTF-8");

			WebResource searchCall = client.resource(searchConceptURL+searchterm);	
			try{
			result = searchCall.accept(MediaType.APPLICATION_JSON_TYPE).cookie(cookies.get(0)).get(String.class);
			}catch(Exception e){
				if (e instanceof UniformInterfaceException){
					throw new Exception(searchterm, e);	
					
				}else{
					e.printStackTrace();
				}
			}

			return result;
			/*if (result.equalsIgnoreCase("null") == false) {
				ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);

				mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
				mapper.configure(Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true);
				JsonNode root = mapper.readTree(result);

				JsonNode jsonConcepts = root.get("IfdConcept");
				
			if (jsonConcepts.isArray()) {
				Iterator<JsonNode> iterator = jsonConcepts.iterator();
				while (iterator.hasNext()) {
					JsonNode jsonNode = iterator.next();
					String conceptInRGuid = jsonNode.get("guid").getTextValue();
					String relationshipType = jsonNode.get("conceptType")
							.getTextValue();
					GuidTypePairs.put(conceptInRGuid, relationshipType);
				}
			}
		}
		return GuidTypePairs;*/
	}
	

	
	private static HashMap<String, String> searchRelationships(String searchString, List<NewCookie> cookies) throws Exception {

		String result = null;
		HashMap<String, String> GuidTypePairs = new HashMap<String, String>();
		
			ClientConfig clientConfig = new DefaultClientConfig();
			clientConfig.getClasses().add(JacksonJsonProvider.class);
			clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
			Client client = Client.create(clientConfig);
			//String s = URLEncoder.encode("*", "UTF-8");

			WebResource searchCall = client.resource(searchString);			
			result = searchCall.accept(MediaType.APPLICATION_JSON_TYPE).cookie(cookies.get(0)).get(String.class);

			if (result.equalsIgnoreCase("null") == false) {
				ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);

				mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
				mapper.configure(Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true);
				JsonNode root = mapper.readTree(result);

				JsonNode jsonRelathionships = root.get("IfdConceptInRelationship");
				
			if (jsonRelathionships.isArray()) {
				Iterator<JsonNode> iterator = jsonRelathionships.iterator();
				while (iterator.hasNext()) {
					JsonNode jsonNode = iterator.next();
					String conceptInRGuid = jsonNode.get("guid").getTextValue();
					String relationshipType = jsonNode.get("relationshipType")
							.getTextValue();
					GuidTypePairs.put(conceptInRGuid, relationshipType);
				}
			}
		}
		return GuidTypePairs;
	}


	
	private void compare(String s) throws Exception {
		String m = new String("B");
		if (s.equals(m)) {
			System.out.println("into if");
			throw new Exception(m);
		}
	}
	
	private void processDB(ObjectContainer db){
		Cat tom = new Cat();
		Cat tomsenoir = new Cat();
		Cat fakeTom = new Cat();
		
		tom.setName("Tom");
		tom.setFather(tomsenoir);
		fakeTom.setName("Tom");
		fakeTom.setFather(tomsenoir);
		
		Mouse jerry = new Mouse();
		
		db.store(tom);
		db.store(tom);
		db.store(tom);
		db.store(tom);
		
		db.store(jerry);
	
		db.commit();
	}
	
	
	private Future<String> callCat(ExecutorService threadPool){
		CatCallable c = new CatCallable();
		return threadPool.submit(c); 
	}
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		
		final String loginUrl = "http://bsddpilot.catenda.no/api/4.0/session/login";
		
		ClientConfig clientConfig = new DefaultClientConfig();
		clientConfig.getClasses().add(JacksonJsonProvider.class);
		clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,Boolean.TRUE);
		Client client = Client.create(clientConfig);
		
		List<NewCookie> cookies = getCookies(client, loginUrl);
		String s1 = searchConcepts("3vHdqCoT0Hsm00051Mm008", cookies);
		
		
			ObjectMapper mapper = ClientUtilities.getMapper();
			JsonNode root = mapper.readTree(s1);
			
			
		
		
		
		//String s2 = searchConcepts("window", cookies);
		System.out.println(root.get("guid").getTextValue());
		
		
		/*JsonNode root1 = null, root2 = null,jConcepts1 = null, jConcepts2 = null;
	
		ObjectMapper mapper = ClientUtilities.getMapper();
		if (s1 != null) {
			
			root1 = mapper.readTree(s1);
			jConcepts1 = root1.get("IfdConcept");
			
		} 
		
		if (s2 != null) {
			
			root2 = mapper.readTree(s2);
			jConcepts2 = root2.get("IfdConcept");
			
		}
		
		
	
		
		ArrayNode tmpArrayNode = mapper.createArrayNode();
		if (jConcepts1.isObject()) {
			if (jConcepts2.isObject()) {
				tmpArrayNode.add(jConcepts1);
				tmpArrayNode.add(jConcepts2);
			} else {
				tmpArrayNode.add(jConcepts1);
				Iterator itr = jConcepts2.iterator();
				while (itr.hasNext()) {
					tmpArrayNode.add((JsonNode) itr.next());
				}
			}
		}else{
			if (jConcepts2.isObject()){
				tmpArrayNode.add(jConcepts2);
				Iterator itr = jConcepts1.iterator();
				while (itr.hasNext()) {
					tmpArrayNode.add((JsonNode) itr.next());
				}
			}else{
				Iterator itr = jConcepts1.iterator();
				while (itr.hasNext()) {
					tmpArrayNode.add((JsonNode) itr.next());
				}
				itr = jConcepts2.iterator();
				while (itr.hasNext()) {
					tmpArrayNode.add((JsonNode) itr.next());
				}
			}
		}
		
		//JsonNode jsonConcepts = tmpArrayNode.get("IfdConcept");
		
	
		
		if (tmpArrayNode != null) {

			if (tmpArrayNode.isArray()) {
				Iterator<JsonNode> it = tmpArrayNode.iterator();
				while (it.hasNext()) {
					JsonNode jsonNode = it.next();
					System.out.println(jsonNode.get("guid").getTextValue());
				}
			}else{
				System.out.println(tmpArrayNode.get("guid").getTextValue());
			}
		}*/
		/*
		
		final String searchRelURL = "http://bsddpilot.catenda.no/api/4.0/IfdConcept/";
		
		ListTest t1 = new ListTest();
		//String  searchConceptGuid = "1J28m0BQyHtm00025QrE$V";
		List<NewCookie> cookies = getCookies(client,loginUrl);
		UniformInterfaceException uifException;	
		HashMap<String, String> GuidTypePairs = new HashMap<String, String>();
		
		try {
			GuidTypePairs = t1.searchConcepts("d*", cookies);
		} catch (Exception e) {
			System.err.println("error cause by:" + e.getMessage());
			if (e.getCause() instanceof UniformInterfaceException) {
				uifException = (UniformInterfaceException) e.getCause();
			switch (uifException.getResponse().getStatus()) {
			case 500:
				System.out.println("we can get statues");
				
				break;
			}
			//e.printStackTrace();
		}
		}
		
		Iterator<String> iter = GuidTypePairs.keySet().iterator();
		while(iter.hasNext()){
			String conceptGuid = (String) iter.next();
			System.out.println(conceptGuid + "<---->" + GuidTypePairs.get(conceptGuid));
			
		}*/
		
		
		
      /* List<Integer> s = new ArrayList<Integer>();
       for (int i = 0; i < 10; i++)
    	   s.add((int)(Math.random()*50) + 50);
       
       System.out.println(s.size());
       for (int i=0; i< s.size(); i++)
    	   if(s.get(i)>75)
    		   s.remove(i);
       System.out.println(s.size());*/
/*		ListTest lt = new ListTest();
		List<String> list = new ArrayList<String>();
		  String a = new String("A");
		  String b = new String("B");
		  String c = new String("C");
		  String d = new String("C");
		  
		  
		  
		 // HashMap<String, Integer> hashmap= new HashMap<String,Integer>();
		  list.add(a);
		  list.add(b);
		  list.add(c);
		  list.add(d);
		  
		  System.out.println("Before for loop  "+list.size());
		 
		  
		  for(int i = 0; i < list.size(); i++){
			  
				  try {
					lt.compare(list.get(i));
					System.out.print(list.get(i)+"  ");
				} catch (Exception e) {
					System.err.print("exception messeage:" + e.getMessage());
					list.add("E");
					list.add("F");
					list.add("G");
				}  
		  }
		 
		  
		  hashmap.put(a, 1);
		  hashmap.put(b, 2);
		  hashmap.put(c, 1);
		  System.out.println(list.size());
		  
		  for(int i = 0; i < list.size(); i++){
			  System.out.print(list.get(i)+"  ");
		  }*/
		 // System.out.println(hashmap.size());
		
		/*ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), "TestDB4.db");
		
		ObjectSet<Cat> catset = db.queryByExample(Cat.class);
		ObjectSet<Cat> mouseset = db.queryByExample(Mouse.class);
		
		System.out.println("Before processing we have " +catset.size() + " cats");
		System.out.println("Before processing we have " +mouseset.size() + " Mouses");
		
		ListTest lt = new ListTest();
		lt.processDB(db);
		
		catset = db.queryByExample(Cat.class);
		mouseset = db.queryByExample(Mouse.class);
		
		
	//	HashSet<Cat> hashset = new HashSet<Cat>();
//		hashset.add(tom);
//		hashset.add(fakeTom);
//		hashset.add(tomsenoir);
		
		System.out.println("After processing we have " +catset.size() + " cats");
		System.out.println("After processing we have " +mouseset.size() + " Mouses");
		
		
		db.close();*/
		
		
/*		String s1 = null;
		String s2 = "{\"pets\": {\"pet\": [{\"name\": \"Tom\",\"adress\": \"cat road\",\"tele\": \"1033\"},{\"name\": \"Jerry\",\"adress\": \"mouse road\",\"tele\": \"2011\"}]}}";
		String s3 = "{ \"ifdConcepts\": \"null\" }";
		ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
		mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.configure(Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
		
		
		JsonNode root = null;
		try {
			root = mapper.readTree(s3);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//JsonNode pets = root.get("pets");
		//JsonNode petset = pets.get("pet");
		JsonNode concepts = root.get("ifdConcepts");
		JsonNode conceptSet = concepts.get("idfConcept");
		
		if (conceptSet == null)
			System.out.println("null node can campare");*/
		
		
//		Iterator<JsonNode> i =petset.iterator();
//		
//		while (i.hasNext()){
//			JsonNode j =  i.next();
//			
//			if(j.get("name").getTextValue().equals("Jerry"))
//				System.out.println(j.get("adress").getTextValue());	
			
//		}
		/*ListTest lt = new ListTest();
		ExecutorService threadPool = Executors.newSingleThreadExecutor();  
        
         
          
        System.out.println("waiting ....");  
          
        try {  
            System.out.println("get result: " + lt.callCat(threadPool).get());  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        } catch (ExecutionException e) {  
            e.printStackTrace();  
        } */
		
		
		
		
	}

}
